var scanpay = {
    config : {
        'buy_scenic_id' : 0, //当前操的景区编号
        'buy_goods_id' : 0, //当前操的门票编号
        'buy_num' : 1,      //当前操的门票数量
        'scrollspy_status' : 0
    },
    timespan : 60,
    _state : true, //jquery validate 验证状态位
    init : function(){
        $this = this;
        $this.config.buy_scenic_id = $('input[name=scenicId]').val(); //初始化
        $this.config.buy_goods_id = $('input[name=ticketId]').val(); //初始化
        scanpay.ticketDescript();
        scanpay.buyTicket();
        scanpay.scanpaySubmit();
        scanpay.sendSmsCaptcha();
        scanpay.orderTicket();
        scanpay.orderTotal();
        scanpay.ticketPop();
        scanpay.selectedTicket();
        scanpay.deleteTicket();
        scanpay.pumAdd();
        scanpay.pumMinus();
        scanpay.pumInput();

        $('.scrollspy-nav').scrollspynav({
            className:{
                active:'am-active',
            }
        });
        if ($('#nav-jjtcc').size() > 0) {
            $('#nav-jjtcc').scrollspy({ //滚动监听
                repeat: false,
                animation: false
                // delay: 500
            });
            $('#nav-jjtcc').on('inview.scrollspy.amui', function() {
                if (scanpay.config.scrollspy_status == 0) {
                    scanpay.config.scrollspy_status = 1;
                    scanpay.scenicNearby();
                    scanpay.tourismNearby();
                    scanpay.hotelNearby();
                    scanpay.zzdyCities();
                    scanpay.restaurantNearby();
                }
            });
        } else {
            scanpay.scenicNearby();
            scanpay.tourismNearby();
            scanpay.hotelNearby();
            scanpay.restaurantNearby();
        }

        // tab页面切换
        $('.ewm-tabs-nav').on('click','li',function(){
            var parent = $(this).parent('.ewm-tabs-nav');
            parent.addClass('ewm-in');
            var height = $('.ewm-tabs').offset().top;
            $('html, body').animate({scrollTop:height},300);
            setTimeout(function(){
                parent.removeClass('ewm-in');
            },300);
        });
    },

    valiMeg : function(msg) {
        if (scanpay._state) { //验证时  一次只弹出一个窗口
            scanpay._state = false;
            alertMessage(msg);
            setTimeout(function(){ //一秒后重新点击
                scanpay._state = true;
            }, 1000);
        }
    },

    ticketDescript : function(){ //预订须知
        $('.scanpay-product-info').on('click', '.buyvive-ticket', function(event) {
            var _id = $(this).attr('data-goods-id');
            $('#buyvive-ticket-'+ _id).modal({'closeViaDimmer':false});
            $('html,body').css('overflow','hidden');
        });
        $('.buy-alert').on('click','.alert-close',function(){ //关闭预定须知
            $('html,body').css('overflow','auto'); 
        })
    },

    buyTicket : function(){ //门票详情
        $('.scanpay-product-info').on('click', '.buy-ticket', function(event) {
            $('#buy-ticket input.num-input').data('max', $(this).data('max')).data('min', $(this).data('min'));
            $('#buy-ticket input[name=goodsId]').val($(this).data('goods-id'));
            $('#buy-ticket p.buy-name').text($(this).data('name'));
            $('#buy-ticket form .buy-Price i').text('￥' + $(this).data('price'));
            $('#buy-ticket form')[0].reset();
            $('#buy-ticket form input[name=quantity]').val($(this).data('min'));
            $('#buy-ticket').modal({'closeViaDimmer':false});
            $('html,body').css('overflow','hidden');//新加，弹框时取消页面滚动
            event.stopPropagation();
        });
    },

    sendSmsCaptcha: function() { //获取短信验证码
        $('.ewm-buy').on('click', 'a.send-captcha', function() {
            var obj = $(this);
            if (!obj.hasClass('disabled')) {
                var mobilePhone = $('input[name=visitor_telephone]').val();
                if (validMobile(mobilePhone)) {
                    obj.addClass("disabled");
                    $.ajax({
                        type: 'post',
                        async: false,
                        dataType: 'json',
                        url: hostUrl() + 'scenic/scanpay/ajaxSendSms',
                        data: {mobilePhone: mobilePhone},
                        beforeSend: function () {},
                        success: function (json) {
                            if (!json.status) {
                                alertMessage(json.messages);
                            } else {
                                scanpay.setSmsTime(obj);
                            }
                        }
                    });
                } else {
                    alertMessage('手机号码格式错误');
                }
            }
        });
    },

    setSmsTime: function(obj) { //初始化发送验证码时间
        if (scanpay.timespan == 0) {
            obj.removeClass("disabled");
            obj.text("获取验证码");
            scanpay.timespan = 60;
        } else {
            obj.text(scanpay.timespan + "重新发送");
            scanpay.timespan--;
            setTimeout(function() {
                scanpay.setSmsTime(obj);
            }, 1000);
        }
    },

    selectedTicket : function(){ //选中指定门票
        $('#scan-scenic-ticket-pop-add').on('click', 'a.vive-rese:not(.active)', function(event){
            $(this).addClass('active'); //防止多次点击
            $this.config.buy_goods_id = $(this).attr('data-goods-id');
            scanpay.orderTicket();

            var fristDelete = $('#scan-scenic-ticket-info .buy-xin');
            // console.log(fristDelete.first().find('.buy-name a.ord-delete').size());
            if (fristDelete.size() > 1 && fristDelete.first().find('.buy-name a.ord-delete').size() <= 0) {
                fristDelete.first().children('.buy-name').append('<a href="javascript:;" class="ord-delete"><i class="iconfont">&#xe611;</i></a>');
            }

            scanpay.orderTotal();
            scanpay.left('.page-1', 'show-4');
            event.stopPropagation();
        });
    },

    deleteTicket : function(){ //移除指定门票
        $('#scan-scenic-ticket-info').on('click','a.ord-delete',function(event){
            $('#my-confirm').modal({
                relatedTarget: this,
                onConfirm: function() {
                    $(this.relatedTarget).parents('.buy-xin').remove();
                    if ($('#scan-scenic-ticket-info .buy-xin').size() < 2) {
                        $('#scan-scenic-ticket-info .buy-name a.ord-delete').remove();
                    }
                    $('.ord-page').height($('.page-1').height());
                    scanpay.orderTotal();
                },
                onCancel: function(){}
            });
            event.stopPropagation();
        });
    },

    orderTicket : function(){ //加载预定门票详情
        if ($('#scan-scenic-ticket-form').size() > 0) {
            $.ajax({
                type: 'post',
                dataType : 'json',
                async : false,
                url: hostUrl() + 'scenic/scanpay/orderTicket',
                data: {scenicId : $this.config.buy_scenic_id, ticketId : $this.config.buy_goods_id},
                beforeSend : function (evt, request, settings) {
                    
                },
                complete : function (evt, request, settings) {
                    // body...
                },
                success: function(data) {
                    if (data.status) {
                        $('#scan-scenic-ticket-info').append(data.messages);
                        if ($('#scan-scenic-ticket-info .buy-xin').size() < 2) {
                            $('#scan-scenic-ticket-info .buy-xin a.ord-delete').remove();
                        }
                    } else {
                        if (data.messages) {
                            window.location.href = data.messages;
                        } else {
                            $('a[href="#ticket-pop-add"]').trigger('click');
                        }
                    }
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
        }
    },

    orderTotal : function(){ //加载预定门票支付总金额
        if ($('#scan-scenic-ticket-form').size() > 0) {
            $.ajax({
                type: 'post',
                dataType : 'json',
                url: hostUrl() + 'scenic/scanpay/orderTotal',
                data: $('#scan-scenic-ticket-form').serialize(),
                beforeSend : function (evt, request, settings) {
                },
                complete : function (evt, request, settings) {
                    // body...
                },
                success: function(data) {
                    if (data.status) {
                        var ticketTotal = data.ticketTotal[$this.config.buy_goods_id]
                        $('.ticketTotal-'+$this.config.buy_goods_id).text(ticketTotal);
                        $('.orderTotal').text(data.orderTotal);
                        $('input[name=required_sfz]').val(data.required_sfz);
                    } else {
                        myalert(data.messages);
                    }
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
        }
    },
    
    ticketPop : function(){ //弹框门票详情
        $('#scan-scenic-ticket-form').on('click','.ord-again',function(event){
            $.ajax({
                type: 'post',
                dataType : 'html',
                url: hostUrl() + 'scenic/scanpay/ticketPop',
                data: $('#scan-scenic-ticket-form').serialize(),
                beforeSend : function (evt, request, settings) {
                    //$('html').css('overflowY', 'hidden'); //隐藏滚动条
                },
                success: function(data) {
                    $('#scan-scenic-ticket-pop-add').html(data);
                    scanpay.right('.page-4','show-4');
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        $('.page-ye').on('click', '.ord-return', function(event){
            var show = $(this).data('return');
            if (show === 'show-3') {
                scanpay.remove();
            }
            scanpay.left('.page-1', show);
            event.stopPropagation();
        });
        $('#scan-scenic-ticket-pop-add').on('click', '.modal-ticket-descript', function(event) {
            var obj = $(this);
            $.ajax({
                type: 'post',
                dataType : 'html',
                url: hostUrl() + 'scenic/scanpay/ticketDescript',
                data: {'goods_id' : obj.attr('data-goods-id')},
                beforeSend : function (evt, request, settings) {
                    $('#modal-ticket-descript').removeClass('hide-loading').modal();
                },
                success: function(data) {
                    $('#modal-ticket-descript').addClass('hide-loading').children('.ticket-contents').html(data);
                },
                ajaxError:function(event, request, settings) {
                    alert('ajaxError');
                }
            });
            event.stopPropagation();
        });
        $('#modal-ticket-descript').on('click', 'a.am-close', function(){
            $('#modal-ticket-descript').modal('close');
        });
    },
    
    pumAdd : function(){ //门票数量加计算
        $('#scan-scenic-ticket-info').on('click', '.num-add', function(event){
            var input=$(this).prev('input');
            var max =input.data('max');
            var input_text=parseInt(input.val());
            $this.config.buy_goods_id = input.attr('data-goods-id');
            if (!(input_text===max)) {
                input.val(input_text+1);
                scanpay.orderTotal();
            } else {
                alertMessage('库存不足或限制购买数量');
            }
            event.stopPropagation();
        });
    },
    
    pumMinus : function(){ //门票数量减计算
        $('#scan-scenic-ticket-info').on('click', '.num-minus', function(event){
            var input=$(this).next('input');
            var min =input.data('min');
            var input_text=parseInt(input.val());
            $this.config.buy_goods_id = input.attr('data-goods-id');
            if (!(input_text==min||input_text<0)) {
                input.val(input_text-1);
                scanpay.orderTotal();
            } else if (input_text > min) {
                alertMessage('限制最低购买数量');;
            }
            event.stopPropagation();
        });
    },
    
    pumInput : function(){ //门票数量修改计算
        $('#scan-scenic-ticket-info').on('blur', '.num-input', function(event){
            var input = parseInt($(this).val(),10);
            var min = $(this).data('min');
            var max = $(this).data('max');
            $this.config.buy_goods_id = $(this).attr('data-goods-id');
            if (isNaN(input) || input===0) {
                $(this).val(min);
            } else if (input>max) {
                $(this).val(max);
            } else {
                $(this).val(input);
            }
            scanpay.orderTotal();
            event.stopPropagation();
        });
    },

    right : function(pageName, showName){
        $('.ord-page').addClass(showName).height($(pageName).height());
        $('.ord-foot').hide();
        $('html, body').scrollTop(0);
    },
    left : function(pageName, showName){
        $('.ord-page').removeClass(showName).height($(pageName).height());
        $('.ord-foot').show();
        $('html, body').scrollTop(0);
    },
    remove : function(){
        $('.go-button').removeClass('active');
        $('.go-people').removeClass('edit');
    },

    scanpaySubmit : function(){ //提交订单操作
        $('#scan-scenic-ticket-form').submit(function(e) {
            e.preventDefault();
        }).validate({
            onclick:false,
            onfocusout:false,
            onkeyup:false,
            focusInvalid:false,
            rules: {
                visitor_telephone: {
                    required : true,
                    mobile : true
                },
                captcha : {
                    required : ($("input[name=captcha]").length > 0) ? true : false,
                    digits : true,
                    rangelength : [6,6]
                },
                visitor_sfz : {
                    checkcard2 : true
                }
            },
            messages: {
                visitor_telephone : {
                    required : '请填写手机号码',
                    rangelength : '手机号码格式错误'
                },
                captcha : {
                    required : '请输入短信验证码',
                    digits : '验证码：6位数字',
                    rangelength : '请输入6位正确的验证码'
                },
                visitor_sfz : {
                    checkcard2 : '身份证格式错误'
                }
            },
            errorPlacement: function(e, el) {
                scanpay.valiMeg(e.text());
            },
            submitHandler: function(f) {
                $.ajax({
                    type: 'post',
                    async: true,
                    dataType : 'json',
                    url: hostUrl()+'scenic/scanpay/scanpaySubmit',
                    data: $('#scan-scenic-ticket-form').serialize(),
                    beforeSend: function() {
                        $('#scan-scenic-ticket-form button[type=submit]').attr('disabled', true).text('加载中...');
                    },
                    success: function(data) {
                        if (data.status) {
                            window.location.href = data.messages;
                        } else {
                            alertMessage(data.messages);
                            $('#scan-scenic-ticket-form button[type=submit]').text('重新提交').removeAttr('disabled');
                        }
                    }
                });
                return true;
            }
        });
    },

    nav : function() {
        $('#nav-jjtcc');
    },

    scenicNearby : function(){ //异步加载附近景区
        if ($('.jingqu').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/scenicNearby',
                data : {sid:$('.jingqu').data('sid'), cityid: $('.jingqu').data('cityid'), provinceid: $('.jingqu').data('provinceid'), flag:true},
                success : function (data) {
                    $('.jingqu').html(data.html);
                }
            });
        } else if($('#nearby-scenic-paySuccess').size() > 0) { // 支付成功页面
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/scenicNearby',
                data : {sid:$('#nearby-scenic-paySuccess').data('sid'), cityid: $('#nearby-scenic-paySuccess').data('cityid'), provinceid: $('#nearby-scenic-paySuccess').data('provinceid')},
                success : function (data) {
                    $('#nearby-scenic-paySuccess').html(data.html);
                }
            });
        }
    },

    tourismNearby : function(){ //异步加载附近特产
        if ($('.techan').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/tourismNearby',
                data : {sid:$('.techan').data('sid'), cityid: $('.techan').data('cityid'), provinceid: $('.techan').data('provinceid'), flag:1},
                success : function (data) {
                    $('.techan').html(data.html);
                }
            });
        } else if ($('#nearby-tourism-paySuccess').size() > 0) { //支付成功页面
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/tourismNearby',
                data : {sid:$('#nearby-tourism-paySuccess').data('sid'), cityid: $('#nearby-tourism-paySuccess').data('cityid'), provinceid: $('#nearby-tourism-paySuccess').data('provinceid')},
                success : function (data) {
                    $('#nearby-tourism-paySuccess').html(data.html);
                }
            });
        }
    },

    hotelNearby : function(){ //异步加载附近酒店
        if ($('.jiudian').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/hotelNearby',
                data : {sid:$('.jiudian').data('sid'), cityid: $('.jiudian').data('cityid'), provinceid: $('.techan').data('provinceid'), flag:1},
                success : function (data) {
                    $('.jiudian').html(data.html);
                }
            });
        } else if ($('#nearby-hotel-paySuccess').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/hotelNearby',
                data : {sid:$('#nearby-tourism-paySuccess').data('sid'), cityid: $('#nearby-hotel-paySuccess').data('cityid'), provinceid: $('#nearby-hotel-paySuccess').data('provinceid')},
                success : function (data) {
                    $('#nearby-hotel-paySuccess').html(data.html);
                }
            });
        }
    },

    zzdyCities : function(){ // 异步加载城市一站通

        if ($('.chengshi').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/zzdyCities',
                data : {cityid: $('.chengshi').data('cityid')},
                success : function (data) {
                    $('.chengshi').html(data.html);
                }
            });
        }
    },

    restaurantNearby : function(){
        if ($('.canyin').size() > 0) {
            $.ajax({
                type : 'get',
                async : true,
                dataType : 'json',
                url : hostUrl() + 'scenic/scanpay/restaurantNearby',
                data : {sid:$('.canyin').data('sid'), flag:true},
                success : function (data) {
                    if (data.status) {
                        $('.canyin').html(data.html);
                    } else {
                        $('#eat-li').remove();
                    }
                    
                }
            });
        } 
        // else if($('#nearby-scenic-paySuccess').size() > 0) { // 支付成功页面
        //     $.ajax({
        //         type : 'get',
        //         async : true,
        //         dataType : 'json',
        //         url : hostUrl() + 'scenic/scanpay/scenicNearby',
        //         data : {sid:$('#nearby-scenic-paySuccess').data('sid'), cityid: $('#nearby-scenic-paySuccess').data('cityid'), provinceid: $('#nearby-scenic-paySuccess').data('provinceid')},
        //         success : function (data) {
        //             $('#nearby-scenic-paySuccess').html(data.html);
        //         }
        //     });
        // }
    }

}

$(function(){
    scanpay.init(); //订单支付页面
});